$(document).ready(function(){
	$("#showNewsInfor").dialog(
		{
			autoOpen:false,
			modal: true, // 设置对话框为模式
			width: 1000,
			title:'新闻详细',
			buttons: {
				"修改":function(){
					updateUser();
				},
				"取消": function() {
					$(this).dialog('close');
	      		}
   		 	}
		}
	);
	
	//搜索新闻
	$("#queryNews").click(function(){
		queryNews();
	});
	
	//删除新闻
	$("#deleteNews").click(function(){
		var selectedId= $("#gridTable").jqGrid("getGridParam", "selrow");
		if(selectedId) {
			deleteNews();
		}else{
			alert("请选择要删除的行");
			return false;
		}

	});
	
	/***
	 * 查看详细
	 */
	$("#detailNews").click(function(){
		var selectedId= $("#gridTable").jqGrid("getGridParam", "selrow");
		if(selectedId) {
			//findDetail();
			var rowData = $("#gridTable").jqGrid("getRowData", selectedId);
			alert(rowData.newsId);
			location.href="admin/news!newsInfor?id="+rowData.newsId;
		}else{
			alert("请选择要要查看的行");
			return false;
		}

	});
	
	$("#updateNews").click(function(){
		var selectedId= $("#gridTable").jqGrid("getGridParam", "selrow");
		if(selectedId) {
			var rowData = $("#gridTable").jqGrid("getRowData", selectedId);
			alert("up");
			location.href="admin/updateNews.jsp?newsId="+rowData.newsId;
		}else{
			alert("请选择要修改的行");
			return false;
		}

	});
	//绑定列表数据
	$("#gridTable").jqGrid({
        url: 'admin/news!searchNewsList',
        datatype: "json",
        height: 250,
        colNames: ['编号', '标题', '关键字', '内容', '点击数','发表日期', '修改日期'],
        colModel: [{
            name: 'newsId',
            index: 'newsId',
			width:50,
            sorttype: 'int',
            editable: true
        }, {
            name: 'title',
            index: 'title',
            editable: true
			
        }, {
            name: 'keyWord',
            index: 'keyWord',
            editable: true
        }, {
            name: 'content',
            index: 'content',
			width:320,
        }, {
            name: 'clickCount',
            index: 'clickCount',
			width:80,
        },{
            name: 'publishTime',
            index: 'publishTime',
			formatter:'date',
			editrules:{date:true},
			search:false,
			editable:false,
			formatoptions:{srcformat:'Y-m-d H:i:s',newformat:'Y-m-d H:i:s'},
			datefmt:'Y-m-d H:i:s',
			width:120,
            editable: true
        }, {
            name: 'modiferTime',
            index: 'modiferTime',
			width:120,
			formatter:'date',
			editrules:{date:true},
			search:false,
			editable:false,
			formatoptions:{srcformat:'Y-m-d H:i:s',newformat:'Y-m-d H:i:s'},
			datefmt:'Y-m-d H:i:s',
            editable: true
        }],
        sortname: 'newsId',
        sortorder: 'desc',
        viewrecords: true,
        rowNum: 10,
        rowList: [10, 20, 30],
        jsonReader: {
            root: "newsList", // 数据行（默认为：rows）   
            page: "page", // 当前页   
            total: "totalPage", // 总页数   
            records: "totalCount", // 总记录数   
            repeatitems: false // 设置成false，在后台设置值的时候，可以乱序。且并非每个值都得设   
        },
		prmNames : {
			search : "search"
		},
        pager: "#gridPager",
        emptyrecords: "没有数据显示",
        multiselect: true,
        caption: "新闻列表"
    });
	
});
function loadJQgrid(){
    $("#gridTable").jqGrid({
        url: 'admin/news!searchNewsList',
        datatype: "json",
        height: 250,
        colNames: ['编号', '标题', '关键字', '内容', '点击数','发表日期', '修改日期'],
        colModel: [{
            name: 'newsId',
            index: 'newsId',
			width:50,
            sorttype: 'int',
            editable: true
        }, {
            name: 'title',
            index: 'title',
            editable: true
			
        }, {
            name: 'keyWord',
            index: 'keyWord',
            editable: true
        }, {
            name: 'content',
            index: 'content',
			width:320,
        }, {
            name: 'clickCount',
            index: 'clickCount',
			width:80,
        },{
            name: 'publishTime',
            index: 'publishTime',
			formatter:'date',
			editrules:{date:true},
			search:false,
			editable:false,
			formatoptions:{srcformat:'Y-m-d H:i:s',newformat:'Y-m-d H:i:s'},
			datefmt:'Y-m-d H:i:s',
			width:120,
            editable: true
        }, {
            name: 'modiferTime',
            index: 'modiferTime',
			width:120,
			formatter:'date',
			editrules:{date:true},
			search:false,
			editable:false,
			formatoptions:{srcformat:'Y-m-d H:i:s',newformat:'Y-m-d H:i:s'},
			datefmt:'Y-m-d H:i:s',
            editable: true
        }],
        sortname: 'newsId',
        sortorder: 'desc',
        viewrecords: true,
        rowNum: 10,
        rowList: [10, 20, 30],
        jsonReader: {
            root: "newsList", // 数据行（默认为：rows）   
            page: "page", // 当前页   
            total: "totalPage", // 总页数   
            records: "totalCount", // 总记录数   
            repeatitems: false // 设置成false，在后台设置值的时候，可以乱序。且并非每个值都得设   
        },
		prmNames : {
			search : "search"
		},
        pager: "#gridPager",
        emptyrecords: "没有数据显示",
        multiselect: true,
        caption: "新闻列表"
    });
   

}

/***
 * 查询新闻
 */
 function queryNews(){
	var sdata = {   //构建查询需要的参数  
        keyword: $("#searchNews").val()    
    };    
    //获得当前postData选项的值  
    var postData = $("#gridTable").jqGrid("getGridParam", "postData");  
      
    //将查询参数融入postData选项对象  
    $.extend(postData, sdata);  
      
    $("#gridTable").jqGrid("setGridParam", {  
        search: true,mtype : "post"    // 将jqGrid的search选项设为true  
    }).trigger("reloadGrid", [{page:1}]);   //重新载入Grid表格，以使上述设置生效   
}


/**********************************/
function deleteNews(){
	var ids = new Array();　//创建一个数组
    var selectedIds =$("#gridTable").jqGrid("getGridParam", "selarrrow");
    if(selectedIds) {
		for(var i=0;i<selectedIds.length;i++)
		{
			var id=jQuery('#gridTable').jqGrid('getCell',selectedIds[i],'newsId');
			ids.push(id);
		}
		ids=ids.toString();
		alert(ids);
		var params={"ids":ids};
			 $.ajax({
            type: "post",
            url: "admin/news!deleteNews",
            data:params,
            dataType: "json",
            success: function(data){
			  $("#gridTable").jqGrid('setGridParam',{url:"admin/news!searchNewsList"}).trigger("reloadGrid");
               if (data == 1) {
                    alert("删除成功！");
               }
               else {
                   alert("删除失败！");
               }
                return true;
            },
            error: function(data){
				$("#gridTable").jqGrid('setGridParam',{url:"admin/user!getUserList"}).trigger("reloadGrid");
                return false;
            }
        });
		
		
		
		/****
		 /var selectedId= $("#gridTable").jqGrid("getGridParam", "selrow");
        var rowData = $("#gridTable").jqGrid("getRowData", selectedId);
        alert("确定要删除第" + selectedId + "行？");
        alert(rowData.userId);**/
       
    }
    else {
        alert("请选择要删除的行");
		return false;
    }
    

}
/**
 * 查看详细
 */
function findDetail(){
	var selectedId= $("#gridTable").jqGrid("getGridParam","selrow");
	var rowData = $("#gridTable").jqGrid("getRowData", selectedId);
		if(selectedId) {
			var replyCount;//跟贴数
			var params;
			 /**查看跟贴**/
			
			params = {
				"newsId": $("#nd").val()
		    };
		    $.ajax({
		        type: "post",
		        url: "admin/reply!replyCount",
		        data: params,
		        dataType: "json",
				async: true,
		        success: function(data){
					replyCount=data;
		            $("#showReplyCount").append(replyCount);// 显示跟贴数
		            return;
		        },
		        error: function(data){
		            alert("error");
		            return;
		        }
		    });
			if(replyCount>0){//查询跟贴列表
				//loadNewsReply(params);
			}
			params={id:rowData.newsId};
			 $.ajax({
			 	type: "post",
			 	url: "admin/news!newsInfor",
			 	data: params,
			 	dataType: "json",
			 	success: function(data){
					$("#showTitle").val();
					$("#showClickCount").val();
					$("#showKeyword").val();
					$("#showPublishTime").val();
					$("#showModiferTime").val();
					$("#showContent").val();
					$("#showTitle").val();
					$("#replyList").val();
					$("#showTitle").append(data.news.title);
					$("#showClickCount").append(data.news.clickCount);
					$("#showKeyword").append(data.news.keyWord);
					$("#showPublishTime").append(data.news.publishTime);
					$("#showModiferTime").append(data.news.modiferTime);
					$("#showContent").append(data.news.content);
					if(replyCount>0){
						for(var i=0;i<replyCount;i++){
							$("#replyList").append(data.news.tbReplies[i].content+"<br>"+data.news.tbReplies[i].tbUser.userName+"&nbsp;"+data.news.tbReplies[i].replyTime+"<br><hr>");
						}
					}
					$("#showNewsInfor").dialog("open");					
			 		return true;
			 	},
			 	error: function(data){
					alert("error");
			 		return false;
			 	}
			 });
			
		}else{
			alert("请选择要查询详细的行");
			return false;
		}
}
/*************查询跟贴信息*************/
function loadNewsReply(params){
	$.ajax({
        type: "post",
        url: "admin/reply!newsFirstReply",
        data: params,
        dataType: "json",
		async : true,
        success: function(data){
           $.each(data.replyList, function(index, element){
		    $("#news_replyList").html("");
            $.each(data.replyList, function(index, element){
				t=element.replyTime.substr(0,10)+" "+element.replyTime.substr(11,18);
                $("#news_replyList").append("<div class='reply_item'>"+element.tbUser.userName+"&nbsp;&nbsp;&nbsp;&nbsp;"+t+"<br>"+element.content+"</div>");
            	});
            });
            return;
        },
        error: function(data){
            alert("load error");
            return;
        }
    });
	 $("#replyListTable").jqGrid({
        url: 'admin/news!searchNewsList',
        datatype: "json",
        height: 250,
        colNames: ['编号', '内容', '回复日期', '修改日期'],
        colModel: [{
            name: 'replyId',
            index: 'replyId',
            width: 60,
            sorttype: "int",
            editable: true
        },],
        sortname: 'newsId',
        sortorder: 'desc',
        viewrecords: true,
        rowNum: 10,
        rowList: [10, 20, 30],
        jsonReader: {
            root: "replyList", // 数据行（默认为：rows）   
            page: "pageIndex", // 当前页   
            total: "totalPage", // 总页数   
            records: "totalCount", // 总记录数   
            repeatitems: false // 设置成false，在后台设置值的时候，可以乱序。且并非每个值都得设   
        },
		prmNames : {
			search : "search"
		},
        pager: "#replyList",
        emptyrecords: "没有数据显示",
        multiselect: true,
        caption: "跟贴列表"
    });
   
}
